/**
 * 
 */
package com.zte.claa.inficombo.csa.app.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationHome;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

/**
 * @author 0283000138
 *
 */
public class IOUtils {
	// 日志记录.
	private static final Logger logger = LoggerFactory.getLogger(IOUtils.class);

	/**
	 * 加载 ClassPath目录下面的文件,并以流的方式返回
	 * @param filepath
	 * @return
	 * @throws IOException
	 */
	public static InputStream loadClassPathResource(String filepath) throws IOException{
		String springBootJarPath = IOUtils.getBaseJarPath();
		logger.info("[@@]springBootJarPath = "+springBootJarPath);
		// 1.这里表示优先从jar同级目录加载
		String tmpFilepath = filepath.replaceAll("\\\\", "/");
		if(tmpFilepath.startsWith("/")){
			tmpFilepath = tmpFilepath.substring(1);
		}
		springBootJarPath = springBootJarPath.replaceAll("\\\\", "/");
		if(springBootJarPath.endsWith("/")){
			springBootJarPath = springBootJarPath.substring(0, springBootJarPath.length()-1);
		}
		File file = new File(springBootJarPath+"/"+tmpFilepath);
		if (file.exists()) {
			logger.info("[@@]file path = "+file.getAbsolutePath());
			return new FileInputStream(file);
		}
		// 2.如果不存在，则从jar内部加载。
		Resource resource = new ClassPathResource(filepath);
		return resource.getInputStream();
	}
	
	/**
	 * 获取springboot的jar所在目录
	 * @return
	 */
	public static String getBaseJarPath() {
	    ApplicationHome home = new ApplicationHome(IOUtils.class);
	    File jarFile = home.getSource();
	    if (jarFile != null && jarFile.getParentFile() != null){
	    	return jarFile.getParentFile().getAbsolutePath();
	    }
	    return "";
	}
}
